package com.shj.web.security;

import com.shj.model.SysUserRole;
import com.shj.service.SysUserRoleService;
import com.shj.web.security.entity.SelfUserEntity;
import com.shj.web.security.service.SelfUserDetailsService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Description TODO 自定义登录验证
 * @Author songhuajian
 * @Date 2020/3/13 0:10
 **/
@Component
public class UserAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private SelfUserDetailsService selfUserDetailsService;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取表单输入的用户名
        String userName = (String) authentication.getPrincipal();
        // 获取表单输入的密码
        String password = (String) authentication.getCredentials();
        // 查询用户是否存在
        SelfUserEntity user = (SelfUserEntity) selfUserDetailsService.loadUserByUsername(userName);
        if (user == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        // 判断密码是否正确，使用BCryptPasswordEncoder进行加密
        if (!new BCryptPasswordEncoder().matches(password, user.getPassword())){
            throw new BadCredentialsException("账号或密码错误");
        }
        // 还可以加其他信息判断，比如用户状态
//        if ("PROHIBIT".equals(user.getStatus())){
//            throw new LockedException("该用户已被冻结");
//        }
        // 角色集合
        Set<GrantedAuthority> authorities = new HashSet<>();
        // 查询用户角色
        List<SysUserRole> roleList = sysUserRoleService.findByUserId(user.getUserId());
        for (SysUserRole sysUserRole : roleList){
            authorities.add(new SimpleGrantedAuthority(sysUserRole.getRoleId()));
        }
        user.setAuthorities(authorities);
        // 登录
        return new UsernamePasswordAuthenticationToken(user, password, authorities);
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
